import os
import sysconfig  # Get path prefix (example: /usr).

from searxqt import SCHEMA_PATH
from searxqt.core.requests import json_schema_load


""" Pre-load json schema objects """
# Get/find path to schema json files.
# Priority:
#  1. Pwd (./searxqt/schema/)
#  2. User (example: ~/.local/share/)
#  3. Sys (example: /usr/share/)
def find_schema_path(schemas):
    def __path_has_schemas(path):
        for key, filename in schemas:
            full_file_path = os.path.join(path, filename)
            if (not os.path.isfile(full_file_path) or
                not os.access(full_file_path, os.R_OK)):
                return None
        return path

    def __get_config_var_schema_path(var):
        path = os.path.join(
            sysconfig.get_config_var(var),
            'share/',
            SCHEMA_PATH
        )
        return __path_has_schemas(path)

    # Pwd path
    path = __path_has_schemas('./data/schema/')
    if path is not None:
        return path

    # User path
    path = __get_config_var_schema_path('userbase')
    if path is not None:
        return path

    # Sys path
    path = __get_config_var_schema_path('prefix')
    if path is not None:
        return path

    return None


def load_schemas():
    # Json schema files to find/use
    schemas = [
        ('searx_space_instances', 'searx_space_instances.json'),
        ('searxng_config'       , 'searxng_config.json'),
        ('searxng_query'        , 'searxng_query.json')
    ]

    # Find path to schema files
    path = find_schema_path(schemas)
    if path is None:
        raise Exception("Could not read json schema file(s), they are either "
                        "missing or we don't have rights to read them.")

    # Load json schema files into objects
    for key, filename in schemas:
        json_schema_load(key, os.path.join(path, filename))


load_schemas()
